const api = {
	url: 'https://xtzwz.winhui.com.cn/',
	// 本地环境
	// url: 'http://192.168.0.124:8018/', //波兄
	// url: 'http://196.168.0.161:8898/',
	// url: 'http://192.168.0.158:8168/',
	color: '#1381ff',
	ver: 'api/v1/apis/',
	obj: uni,
	// 没有登录，默认跳转登录页面
	home: '/pages/login/login',
	// 用于新增、编辑表单提交时，传给后端用于判断
	sceneStore: 'store',
	sceneUpdate: 'update',

	is_tel(tel) {
		return /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/.test(tel)
	},
	scanCode() {
		return new Promise((resove, reject) => {
			this.loading()
			this.obj.scanCode({
				onlyFromCamera: true,
				scanType: ['qrCode'],
				success: res => {
					resove(res.result)
				},
				complete: () => {
					this.obj.hideLoading()
				}
			})
		})
	},
	authorize(scope) {
		if (!scope) return
		return new Promise((resove, reject) => {
			this.obj.authorize({
				scope: scope,
				success: () => {
					resove()
				},
				fail: () => {
					this.alert('授权失败').then(() => {
						this.obj.openSetting()
					})
				}
			})
		})
	},
	save(url) {
		if (!url) return
		this.authorize('scope.writePhotosAlbum').then(() => {
			this.loading()
			this.obj.downloadFile({
				url: url,
				success: res => {
					this.obj.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: () => {
							this.alert('保存成功')
						}
					})
				},
				complete: () => {
					this.obj.hideLoading()
				}
			})
		})
	},
	loading(title, mask) {
		this.obj.showLoading({
			title: title || '',
			mask: mask || true
		})
	},
	msg(title, icon) {
		this.obj.showToast({
			icon: icon || 'none',
			title: title
		})
	},
	alert(params) {
		var content = ''
		if (params.content) {
			content = params.content
		} else if (params.msg) {
			content = params.msg
		} else if (params.message) {
			content = params.message
		}
		let options = {
			title: '',
			data: {},
			url: '',
			showCancel: false,
			cancelText: '取消',
			confirmText: '确定',
			content: content,
			method: params.method || 'POST'
		}
		if (typeof params == 'object') {
			options = {
				...options,
				...params
			}
		}
		let {
			url,
			data,
			method
		} = options
		return new Promise((resove, reject) => {
			this.obj.showModal({
				...options,
				confirmColor: this.color,
				cancelColor: '#999',
				success: res => {
					let confirm = res.confirm || false
					if (!url) {
						resove(confirm)
						return
					}
					if (confirm) {
						this.loading()
						resove(this.get(url, data, method))
					}
				}
			})
		})
	},
	confirm(params) {
		if (typeof params == 'string') {
			params = {
				url: params
			}
		}
		let options = {
			content: '确定要删除吗?',
			title: '删除提示',
			showCancel: true,
			method: 'DELETE',
			...params
		}
		return this.alert(options)
	},
	get(url, params, method, loa) {
		let linshi_url = url;
		params = params || {}
		// console.log(url)
		method = method || 'GET'
		var token = this.cache('token')
		var auth = params.auth || 0
		var current_page = params.current_page || 0
		params.current_page = 0
		var last_page = this.cache('last_page' + JSON.stringify(params)) || 1
		var ver = this.ver
		if (~url.search(/(pay)/)) ver = ''

		// 白名单
		if (['wxtel', 'get_mobile_phone', 'getopenid'].includes(url)) {
			ver = ver.replace('apis', 'xcx')
		}
		if (['users/details', 'users/userpw_login'].includes(url)) {
			ver = ver.replace('apis/', '')
		}

		// url = this.url + ver + url
		// 判断url是否含有/api/v1，有则不需要再添加
		if (url.includes('/api')) {
			url = this.url + url.slice(1);
		} else {
			url = this.url + ver + url
		}
		if (loa != 'none') {
			this.loading('请求中...')
		}



		// var loading = params.loading || 0
		// if (loading || method == 'GET') {
		// 	this.loading('请求中...')
		// }
		var device_type = window ? 'H5' : 'MP'
		var trade_type = 'JSAPI'
		//#ifdef APP-PLUS
		device_type = plus.os.name.toUpperCase()
		trade_type = 'APP'
		//#endif


		// 处理data
		// 请求必备参数
		let requestNecessaryData = {
			// page: current_page,
			token: token
		};
		// 判断请求方式是get，添加page参数
		if (method == 'GET' || method == 'get') {
			requestNecessaryData['page'] = current_page;
		}


		// 新建立一个json
		let newParams = {};

		// console.log("dsd",params);

		// 将数组对象组成xxx[numb]形式参数给后端，后端才能接收
		// for(let item in params){
		// 	let numb = 0;
		// 	if(params[item].constructor == Object || params[item].constructor == Array){

		// 		for(let ite in params[item]){

		// 			newParams[item + "["+numb+"]"] = params[item][ite];

		// 			numb++;
		// 		}

		// 		if(params[item].constructor == Array&&!params[item].length){

		// 			newParams[item] = [];

		// 		}
		// 		continue;
		// 	}
		// 	// 不是数组的元素直接放入
		// 	newParams[item] = params[item];
		// }
		let c = 0;



		this.fenjie_shuzhu(params, "", newParams, c)



		// 合并数组
		let mergeData = Object.assign(requestNecessaryData, newParams);

		return new Promise((resove, reject) => {
			if (!this.url) return
			if (auth && !token) return
			if (++current_page > last_page) return
			this.obj.request({
				url: url,
				// data: {
				// 	page: current_page,
				// 	device_type: device_type,
				// 	trade_type: trade_type,
				// 	token: token,
				// 	...params
				// 	// params
				// },
				data: mergeData,
				header: {
					token: token,
					Authorization: 'Bearer ' + this.cache('Authorization'),
					'content-type': 'application/x-www-form-urlencoded'
				},
				method: method,
				success: res => {
					if (method == 'GET') {
						var data = res.data.data
						var last_page = data && data.last_page || 1
						this.cache('last_page' + JSON.stringify(params), last_page)
					}

					var statusCode = res.data.code
					if (res.data && res.data.code == 401001) {
						this.cache('token', 0)
						this.alert(res.data).then(() => {
							this.obj.reLaunch({
								url: '/pages/login/login'
							})
						})
						return
					}
					if (statusCode == 401) {
						this.cache('token', 0)
						this.cache("infoData", '')
						// this.alert(res.data).then(() => {
						this.obj.reLaunch({
							url: this.cache('home') || this.home
						})
						// })
						return
					}
					if (statusCode != 200) {
						// if (method != 'GET') {
						this.alert(res.data)
						// }
						return
					}
					//判断会员信息是否微信授权
					if (linshi_url == "users/0" && method == "GET") {
						if (!res.data.data.nick_name || !res.data.data.nickName) {
							uni.navigateTo({
								url: "/pages/user/shouquan"
							})
						}
					}
					resove(res.data)
				},
				complete: () => {
					this.obj.stopPullDownRefresh()
					this.obj.hideNavigationBarLoading()
					this.obj.hideLoading({
						fail: res => {}
					})
				}
			})
		})
	},


	/**
	 * 搜索专用请求
	 * @param {Object} url
	 * @param {Object} params
	 * @param {Object} method
	 */
	getSearch(url, params, method) {
		let linshi_url = url;
		params = params || {}
		// console.log(method)
		method = method || 'GET'
		var token = this.cache('token')
		var auth = params.auth || 0
		var current_page = params.current_page || 0
		params.current_page = 0
		var last_page = this.cache('last_page' + JSON.stringify(params)) || 1
		var ver = this.ver
		if (~url.search(/(pay)/)) ver = ''

		// url = this.url + ver + url
		// 判断url是否含有/api/v1，有则不需要再添加
		if (url.includes('/api')) {
			url = this.url + url.slice(1);
		} else {
			url = this.url + ver + url
		}

		this.loading('请求中...')


		// var loading = params.loading || 0
		// if (loading || method == 'GET') {
		// 	this.loading('请求中...')
		// }
		var device_type = window ? 'H5' : 'MP'
		var trade_type = 'JSAPI'
		//#ifdef APP-PLUS
		device_type = plus.os.name.toUpperCase()
		trade_type = 'APP'
		//#endif

		// 处理data
		// 请求必备参数
		let requestNecessaryData = {
			page: current_page,
			token: token
		};

		let mergeData = Object.assign(requestNecessaryData, params);
		return new Promise((resove, reject) => {
			if (!this.url) return
			if (auth && !token) return
			if (++current_page > last_page) return
			this.obj.request({
				url: url,
				data: mergeData,
				header: {
					token: token,
					Authorization: 'Bearer ' + this.cache('Authorization'),
					'content-type': 'application/x-www-form-urlencoded'
				},
				method: method,
				success: res => {

					if (method == 'GET') {
						var data = res.data.data
						var last_page = data && data.last_page || 1
						this.cache('last_page' + JSON.stringify(params), last_page)
					}
					if (res.data && res.data.code == 401001) {
						this.cache('token', 0)
						this.alert(res.data).then(() => {
							this.obj.reLaunch({
								url: '/pages/login/login'
							})
						})
						return
					}
					var statusCode = res.statusCode
					if (statusCode == 401) {
						this.cache('token', 0)
						this.alert(res.data).then(() => {
							this.obj.reLaunch({
								url: this.cache('home') || this.home
							})
						})
						return
					}
					if (statusCode != 200) {
						if (method != 'GET') {
							this.alert(res.data)
						}
						return
					}
					//判断会员信息是否微信授权
					if (linshi_url == "users/0" && method == "GET") {
						if (!res.data.data.nick_name || !res.data.data.nickName) {
							uni.navigateTo({
								url: "/pages/user/shouquan"
							})
						}
					}
					resove(res.data)
				},
				complete: () => {
					this.obj.stopPullDownRefresh()
					this.obj.hideNavigationBarLoading()
					this.obj.hideLoading({
						fail: res => {}
					})
				}
			})
		})
	},


	put(url, data, method) {
		this.loading()
		return this.get(url, data, method || 'PUT')
	},
	post(url, data, method) {
		this.loading()
		return this.get(url, data, method || 'POST')
	},
	cache(key, data) {
		key += this.url
		if (data == undefined) {
			return this.obj.getStorageSync(encodeURIComponent(key)) || ''
		}
		this.obj.setStorageSync(encodeURIComponent(key), data)
	},
	logout(url) {
		return this.confirm({
			title: '退出提示',
			content: '你确定要退出吗?'
		}).then(btn => {
			if (btn) {
				this.cache('token', 0);
				console.log('url', url)
				this.obj.reLaunch({
					url: url || (this.cache('home') || this.home)
				});
			}
		});
	},
	commons_version(url) {
		var result = {
			code: 200,
			msg: '已经是最新版啦',
			data: null
		}
		//#ifndef APP-PLUS
		return new Promise((resove, reject) => {
			var version = this.cache('version') || '1.0.0';
			var versionCode = this.cache('versionCode') || 100;
			this.cache('version', version);
			this.cache('versionCode', versionCode);
			result.version = version
			result.versionCode = versionCode
			resove(result)
		})
		//#endif
		var type = 0;
		return new Promise((resove, reject) => {
			switch (plus.os.name.toLowerCase()) {
				case 'ios':
					type = 2;
					break;
				case 'android':
					type = 1;
					break;
			}
			plus.runtime.getProperty(plus.runtime.appid, res => {
				var {
					version,
					versionCode
				} = res;
				result = {
					...result,
					...res
				}
				this.cache('version', version);
				this.cache('versionCode', versionCode);
				if (!url) {
					plus.nativeUI.closeWaiting();
					resove(result)
					return
				}
				this.get(url, {
					type: type,
					version: version
				}).then(res => {
					result = {
						...result,
						...res
					}
					resove(result)
				});
			});
		})
	},
	commons_login(options) {
		return new Promise((resove, reject) => {



			//#ifdef H5
			resove(options)
			return
			//#endif
			let scene = this.cache('scene');
			// console.log(scene)
			let lx = 0;
			let d = {};
			if (scene) {
				let jj = scene.split("_")
				if (jj.length == 2) {
					d.scene = jj[0];
					lx = jj[1];
				} else {
					d.scene = scene;
				}
			}
			this.obj.login({
				success: res => {
					// commons/login/mp
					this.post('commons/login/password', {
						code: res.code,
						...d
					}).then(res => {
						if (res.code != 200) {
							this.alert(res.msg)
							return
						}
						this.cache('token', res.data)
						res.lx = lx;
						resove(res)

					})
				}
			})
		})
	},
	pay(params) {
		let options = {
			pay_type: 1,
			message: '',
			order_id: 0,
			url: 'pay',
			...params
		}
		return new Promise((resove, reject) => {
			this.loading()
			this.get(options.url, options).then(res => {
				if (res.code != 200) {
					this.alert(res.msg)
					return
				}
				let config = res.data
				if (!config) {
					reject(res)
					return
				}
				//#ifndef H5
				this.obj.requestPayment({
					...config,
					success: res => {
						resove(res)
					},
					fail: res => {
						reject(res)
						//this.alert(res.errMsg || '支付失败')
					}
				})
				//#endif
			})
		})
	},
	users_id(e, input, id) {
		let {
			userInfo
		} = e.detail
		return new Promise((resove, reject) => {
			if (userInfo) {
				input = {
					img: userInfo.avatarUrl,
					nick_name: userInfo.nickName,
					...input
				}
			}
			if (!input) return
			this.post('users/' + id || 0, {
				input: input
			}).then(res => {
				if (res.code != 200) {
					this.alert(res.msg)
					return
				}
				resove(res)
			})
		})
	},
	chooseMedia() {
		return new Promise((resove, reject) => {
			this.obj.chooseMedia({
				success: res => {
					resove(res)
				}
			})
		})
	},
	chooseVideo() {
		return new Promise((resove, reject) => {
			this.obj.chooseVideo({
				success: res => {
					resove(res)
				}
			})
		})
	},
	chooseImage(count) {
		return new Promise((resove, reject) => {
			this.obj.chooseImage({
				count: count || 1,
				success: res => {
					resove(res)
				}
			})
		})
	},
	upload(tempFiles, i, files) {
		var string = 0
		if (typeof tempFiles == 'string') {
			string = 1
			var tempFiles = [{
				img: '',
				video: '',
				path: tempFiles
			}]
		}
		files = files || []
		i = i || 0
		tempFiles = tempFiles || []
		var len = tempFiles.length
		var url = this.url

		return new Promise((resove, reject) => {
			if (!len || !url) {
				resove(files)
				return
			}
			var data = tempFiles[i]
			var tempFilePath = data.tempFilePath || data.path
			var thumbTempFilePath = data.thumbTempFilePath || ''
			var regExp = new RegExp(url)
			var id = data.id || regExp.test(tempFilePath)

			//#ifdef H5
			var id = !/^(blob)\:/.test(tempFilePath)
			//#endif
			this.loading()

			if (id) {
				// console.log(data)
				files.push({
					img: data.img,
					video: data.video,
					path: tempFilePath
				})
				i++
				if (i < len) {
					resove(this.upload(tempFiles, i, files))
					return
				}
				this.obj.hideLoading()
				resove(string ? files[0] : files)
				return
			}
			// this.api.alert(JSON.stringify(tempFilePath))
			this.obj.uploadFile({
				url: url + 'api/v1/upload/img_upload',
				filePath: tempFilePath,
				name: 'img',
				header: {
					token: this.cache('token')
				},
				success: res => {
					this.obj.hideLoading()
					resove(JSON.parse(res.data))
					// if (res.code == 200) {
					// 	files.push({
					// 		img: res.data[0].img,
					// 		video: res.data[0].video,
					// 		path: res.data[0].path
					// 	})
					// 	i++
					// 	if (i < len) {
					// 		resove(this.upload(tempFiles, i, files))
					// 		return
					// 	}
					// 	this.obj.hideLoading()
					// 	resove(string ? files[0] : files)
					// }
				},
				fail: (e) => {
					console.log("777", e)
					this.obj.hideLoading()
				}
			})
		})
	},

	/**
	 * 跳转页面
	 * @param {Object} url 路径
	 */
	go(url) {
		uni.navigateTo({
			url: url,
		})
	},
	/**
	 * 页面跳转，尽量统一用这里，集中处理跳转逻辑
	 * @param {Object} url 跳转链接
	 * @param {Object} params 跳转参数
	 */
	goCre(url, params) {
		// 随便设置，方便后面直接&拼接
		url += "?g=1";
		// console.log("api.js ********* url: " + url);
		// console.log("params: " + JSON.stringify(params));

		if (params) {
			if (params.url) {
				url += "&url=" + params.url;
			}
			if (params.method) {
				url += "&method=" + params.method;
			}
			if (params.uri) {

				let uri = encodeURIComponent(JSON.stringify(params.uri));

				url += "&uri=" + uri;
			}
			if (params.actionUrl) {
				let actionUrl = encodeURIComponent(JSON.stringify(params.actionUrl));
				url += "&actionUrl=" + actionUrl;
			}
		}

		this.go(url);
	},
	/**
	 * 获取当前页面路由
	 */
	getPageRoute() {
		let param = '?';

		// 获取当前打开过的页面路由数组
		let currentRoutes = getCurrentPages();
		//获取当前页面路由
		let currentRoute = currentRoutes[currentRoutes.length - 1].route;
		//获取路由参数
		let currentParam = currentRoutes[currentRoutes.length - 1].options;

		// 拼接路由参数
		for (let key in currentParam) {
			let jsonKey = typeof(currentParam[key]) == 'object' ? encodeURIComponent(JSON.stringify(currentParam[key])) :
				currentParam[key];
			// param += key + '=' + currentParam[key] + "&"
			param += key + '=' + jsonKey + "&"

		}

		let localRoute = currentRoute + param;
		// console.log(localRoute);
		return localRoute;
	},



	/**
	 * 保存页面路由到缓存
	 * @param {Object} pageRoute
	 */
	savePageRouteCache(pageRoute) {

		let pageRouteArray = [];

		// 缓存读取页面路由数组
		let pageRouteArrayCache = this.cache('pageRouteArray');

		if (pageRouteArrayCache != '') {
			pageRouteArray = pageRouteArrayCache;
		}

		// console.log("====" ,encodeURIComponent(JSON.stringify(pageRoute)));
		pageRouteArray.push(pageRoute)

		this.cache('pageRouteArray', pageRouteArray);
		// console.log("保存页面路由到缓存" ,pageRouteArray);
	},


	dedddddd() {
		// uni.removeStorageSync('pageRouteArray');
		uni.removeStorage({
			key: 'pageRouteArray',
			success: function(res) {
				console.log(res)
			}
		});
		console.log("删除");
	},


	/**
	 * 从缓存获取页面保存路由
	 */
	getPageRouteCache() {
		return this.cache('pageRouteArray');
	},


	/**
	 * 从页面路由缓存中回退上一级
	 */
	backPageRouteCache() {

		// 从缓存中获取页面保存路由，数据形式为数组
		let getPageRouteArrayCache = this.getPageRouteCache();
		// 获取路由数组长度
		let pagePagelength = getPageRouteArrayCache.length;

		if (pagePagelength == 0) {
			console.log("数组路由长度为0");
			// history.back();
			return;
		}

		// 导航文字路径显示
		this.navigationContext();

		// 目标路由
		let targetPageRoute = getPageRouteArrayCache[pagePagelength - 1];
		// 从数组中删除最后一个元素
		getPageRouteArrayCache.pop();
		// 将新数组重新保存到缓存中
		this.cache('pageRouteArray', getPageRouteArrayCache);
		// 通过浏览器退回上一步,但是不触发刷新，如果用history.back刷新逻辑需要另外写
		// history.back();
		// 拼接跳转路径
		targetPageRoute = "../../" + targetPageRoute;
		// 跳转页面
		this.go(targetPageRoute);
	},

	/**
	 * 获取并保存浏览器路由
	 */
	getAndSavePageRoute() {
		// 获取当前页面浏览器路由
		let pageRoute = this.getPageRoute();
		// console.log("获取当前路由：" + pageRoute);
		// 保存页面路由
		this.savePageRouteCache(pageRoute);
	},

	/**
	 * 导航文字路径显示
	 * @param {Object} content 内容
	 */
	navigationContext(content) {

		let modelNameTitleCache = this.cache("modelNameTitle");
		// content有值的时候，在原来的内容基础上进行拼接
		if (content) {
			store.state.currentNavFullTitle = modelNameTitleCache + "-" + content;
			this.cache("modelNameTitle", store.state.currentNavFullTitle);
			return;
		}
		// 没有值的时候，剔除最后的”-’内容‘”
		store.state.currentNavFullTitle = modelNameTitleCache.substring(0, modelNameTitleCache.lastIndexOf('-'));
		this.cache("modelNameTitle", store.state.currentNavFullTitle)
	},

	/**
	 * 获取json长度
	 * @param {Object} jsonData json数据
	 */
	getJsonLength(jsonData) {
		let jsonLength = 0;

		for (let item in jsonData) {
			jsonLength++;
		}
		return jsonLength;
	},
	/**
	 * 获取json最后一个key
	 * @param {Object} jsonData
	 */
	getJSONLastKey(jsonData) {

		let lastKey = 0;

		for (let item in jsonData) {
			lastKey = item;
		}
		return lastKey;
	},
	fenjie_shuzhu(it, linshi, zhi, c) {


		let dancheng = JSON.parse(JSON.stringify(linshi))

		let d = 0;

		for (let i in it) {

			d = 1;

			if (c == 0) {
				linshi = i;
			} else {
				linshi = dancheng + '[' + i + ']';
			}
			// console.log(it[i])

			if (it[i] != undefined) {

				if ((it[i].constructor == Array || it[i].constructor == Object)) {

					let d = c + 1;

					this.fenjie_shuzhu(it[i], linshi, zhi, d)

				} else {

					// console.log("it[i]",it[i])

					// zhi[linshi] = it[i]||[];
					zhi[linshi] = it[i] === 0 ? 0 : it[i] || [];
				}
			}

		}

		if (!d) {
			zhi[linshi] = [];
		}


	},
	jiazai_value(this_) {

		// console.log("this_.jiankong_index",this_.jiankong_index)

		if (this_.datas) {

			if (this_.datas.name == "type") {

				// console.log("[[[[]]]]",this.datas)

				if (!Boolean(this_.datas.value)) {


				} else {

					if (this_.datas.value.constructor == Array && this_.datas.value.length <= 0) {

					} else {
						getApp().globalData.typedd = this_.datas.value;
					}


				}
			}
		}


		if (!Boolean(this_.jiankong_index) || this_.jiankong_index == -1) {
			setTimeout(function() {
				if (this_.datas.broadcast) {
					// console.log("index",this_.jiankong_index)

					if (this_.datas.broadcast.constructor == Array) {

						for (let i in this_.datas.broadcast) {

							if (Boolean(this_.datas.value) && this_.datas.broadcast[i]) {


								getApp().globalData[this_.datas.broadcast[i]] = {
									value: this_.datas.value,
									text: this_.datas.broadcast[i]
								};
							}
						}
					} else {

						if (this_.datas.broadcast.constructor == String) {

							if (Boolean(this_.datas.value)) {

								getApp().globalData[this_.datas.broadcast] = {
									value: this_.datas.value,
									text: this_.datas.broadcast
								};
							}

						}
					}
				}


			}, 500)
		}


	},
	fubiao_xizhi(this_) { //用于副表可以添加多个格式
		if (Boolean(this_.datas.value) && this_.datas.value && JSON.stringify(this_.datas.value) != '[]') {

			for (let i = 0; i < this_.datas.value.length; i++) {

				if (!Boolean(this_.linshi)) {


					for (let i2 in this_.datas.value[i]) {


						if (this_.datas.value[i][i2] && this_.datas.value[i][i2].constructor == Object) {

							// console.log("this_.datas.value[i][i2]",this_.datas.value[i][i2])
							for (let i3 in this_.datas.datas) {


								for (let i5 in this_.datas.value[i][i2]) {
									// console.log("i3",this_.datas.datas[i3].name == i5)

									if (this_.datas.datas[i3].name == i5) {

										//console.log(this_.datas.datas[i3],this_.datas.value[i][i2][i5])

										this_.$set(this_.datas.datas[i3], 'value', this_.datas.value[i][i2][i5])

										if (this_.datas.datas[i3].broadcast && this_.datas.value[i][i2]) {

											getApp().globalData.jiankong_index = i;

											if (this_.datas.datas[i3].broadcast.constructor == Array) {

												for (let i4 in this_.datas.datas[i3].broadcast) {

													if (this_.datas.datas[i3].broadcast[i4]) {
														setTimeout(function() {
															getApp().globalData[this_.datas.datas[i3].broadcast[i4]] = {
																value: this_.datas.value[i][i2],
																text: this_.datas.datas[i3].broadcast[i4],
																jiankong_index: i
															};
														}, 500)
													}


												}

											} else {
												if (this_.datas.datas[i3].broadcast) {
													setTimeout(function() {

														getApp().globalData[this_.datas.datas[i3].broadcast] = {
															value: this_.datas.value[i][i2],
															text: this_.datas.datas[i3].broadcast,
															jiankong_index: i
														};
													}, 500)
												}
											}

										}



									}



								}
							}

						} else {
							for (let i3 in this_.datas.datas) {

								if (this_.datas.datas[i3].name == i2) {

									this_.$set(this_.datas.datas[i3], 'value', this_.datas.value[i][i2])

									if (this_.datas.datas[i3].broadcast && this_.datas.value[i][i2]) {

										getApp().globalData.jiankong_index = i;

										if (this_.datas.datas[i3].broadcast.constructor == Array) {

											for (let i4 in this_.datas.datas[i3].broadcast) {

												if (this_.datas.datas[i3].broadcast[i4]) {
													setTimeout(function() {
														getApp().globalData[this_.datas.datas[i3].broadcast[i4]] = {
															value: this_.datas.value[i][i2],
															text: this_.datas.datas[i3].broadcast[i4],
															jiankong_index: i
														};
													}, 500)
												}


											}

										} else {
											if (this_.datas.datas[i3].broadcast) {
												setTimeout(function() {

													getApp().globalData[this_.datas.datas[i3].broadcast] = {
														value: this_.datas.value[i][i2],
														text: this_.datas.datas[i3].broadcast,
														jiankong_index: i
													};
												}, 500)
											}
										}

									}

								} else {
									if (this_.linshi_data && JSON.stringify(this_.linshi_data) != '{}') {

										if (this_.datas.value[i][i2] && this_.datas.value[i][i2].constructor == Array && this_.datas
											.value[i][i2].length && this_.datas.value[i][i2][0].constructor == Object) {
											//如果他找不到就是因为他是组件内datas  里面 组件的数据
											if (!this_.linshi_data.value) {
												this_.$set(this_.linshi_data, 'value', this_.datas.value[i][i2])
												console.log("如果他找不到就是因为他是组件内", this_.linshi_data)
											}


										}
									}

								}
							}
						}


					}

				} else {


					let linshi = JSON.parse(JSON.stringify(this_.datas))

					for (let i2 in linshi.value[i]) {

						for (let i3 in linshi.datas) {

							if (linshi.datas[i3].name == i2 || this_.datas.datas[i3].name.indexOf(i2 + "[") >= 0) {





								if (linshi.value[i][i2] && linshi.value[i][i2].constructor == Object) {

									for (let i5 in linshi.value[i][i2]) {


										if (linshi.datas[i3].name == i5) {

											// console.log("linshi.value[i][i2]",linshi.value[i][i2])
											this_.$set(linshi.datas[i3], 'value', linshi.value[i][i2][i5])

											if (linshi.datas[i3].broadcast) {

												getApp().globalData.jiankong_index = i;

												if (linshi.datas[i3].broadcast.constructor == Array) {

													for (let i4 in linshi.datas[i3].broadcast) {

														if (linshi.datas[i3].broadcast[i4]) {
															setTimeout(function() {
																getApp().globalData[linshi.datas[i3].broadcast[i4]] = {
																	value: linshi.value[i][i2][i5],
																	text: linshi.datas[i3].broadcast[i4],
																	jiankong_index: i
																};
															}, 500)
														}

													}

												} else {
													setTimeout(function() {
														getApp().globalData[linshi.datas[i3].broadcast] = {
															value: linshi.value[i][i2][i5],
															text: linshi.datas[i3].broadcast,
															jiankong_index: i
														};
													}, 500)

												}



											}
										}

									}



								} else {

									this_.$set(linshi.datas[i3], 'value', linshi.value[i][i2])

									if (linshi.datas[i3].broadcast) {

										getApp().globalData.jiankong_index = i;

										if (linshi.datas[i3].broadcast.constructor == Array) {

											for (let i4 in linshi.datas[i3].broadcast) {

												if (linshi.datas[i3].broadcast[i4]) {
													setTimeout(function() {
														getApp().globalData[linshi.datas[i3].broadcast[i4]] = {
															value: linshi.value[i][i2],
															text: linshi.datas[i3].broadcast[i4],
															jiankong_index: i
														};
													}, 500)
												}

											}

										} else {
											setTimeout(function() {
												getApp().globalData[linshi.datas[i3].broadcast] = {
													value: linshi.value[i][i2],
													text: linshi.datas[i3].broadcast,
													jiankong_index: i
												};
											}, 500)

										}



									}

								}


							}

						}
					}


					//JSON.parse(JSON.stringify(linshi.datas))
					// this_.linshi[i] = linshi.datas;

					// console.log("fdsfs6666",linshi.datas,this_.linshi)
					this_.linshi.push(JSON.parse(JSON.stringify(linshi.datas)));
					// this_.$set(this_.linshi,i,linshi.datas)




				}


			}

			return;
		}

		if (Boolean(this_.linshi)) {
			let linshi = JSON.parse(JSON.stringify(this_.datas))

			getApp().globalData.jiankong_index = 0;
			this.qudiao_kong(linshi.datas);

			this_.linshi.push(linshi.datas)
		}



	},
	fubiao_jiankong_fuzhi_index(it, it2) {


		for (let i in it) {

			if (Boolean(it2[i])) {

				if (Boolean(it2[i].datas) && it2[i].datas.constructor == Object) {

					this.linshi_datas(it[i], it2[i])
				} else {

					if (Boolean(it2[i].datas)) {
						it[i].datas = it2[i].datas;
					} else {
						if (it2[i].value) {
							it[i].value = it2[i].value;
						}

					}



				}

			}

		}
	},
	qudiao_kong(it) {

		for (let i in it) {

			if (Boolean(it[i].datas) && it[i].datas.constructor == Object) {

				this.qudiao_kong(it[i])
			} else {

				if (it[i].value == '[]') {

					it[i].value = "";
				}

			}


		}

	},
	huanzhi(value, it) {


		if (value && it && it.constructor == Array) {
			let zhi = "";
			for (let i in it) {

				let dhfg = (value + "").split(',');

				if (dhfg.length == 1) {
					if (Boolean(it[i].value) && it[i].value == dhfg[0]) {
						return it[i].text;
					}
				}

				//this.duoji_huanzhi(dhfg,it[i],0,zhi)


			}
			// if(zhi==""){
			// 	return value;
			// }else{
			// 	return zhi;
			// }
			return value;
		} else {
			return value;
		}


	},
	duoji_huanzhi(it, it2, d = 0, zhi) {



		if (Boolean(it2.value) && it2.value == it[d]) {

			console.log("it2.value,", it2.text)

			zhi = zhi + it2.text;
			// d++;
			// if(d<it.length&&Boolean(it2.children)){
			// 	this.duoji_huanzhi(it,it2.children,d,zhi)
			// }

		}

	},
	objKeySort(arys) {
		//先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获	取的属性名进行排序，newkey是一个数组
		var newkey = Object.keys(arys).sort();
		//console.log('newkey='+newkey);
		var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
		for (var i = 0; i < newkey.length; i++) { //遍历newkey数组
			newObj[newkey[i]] = arys[newkey[i]]; //向新创建的对象中按照排好的顺序依次增加键值对
		}
		return {
			minKey: newkey[0],
			maxKey: newkey[newkey.length - 1],
			obj: newObj,
		}; //返回排好序的新对象
	},
}

module.exports = api

let _pages = []

function initPage() {
	let oldPage = Page
	Page = function(obj) {
		let oldOnLoad = obj.onLoad || function() {}
		let oldOnUnload = obj.onUnload || function() {}
		obj.onLoad = function() {
			loadStore.call(this)
			this.setState = function(obj) {
				setState.call(this, obj)
			}
			oldOnLoad.call(this, ...arguments)
		}
		obj.onUnload = function() {
			unloadStore.call(this)
			oldOnUnload.call(this, ...arguments)
		}
		return oldPage(obj)
	}
}

function initComponent() {
	let oldComponent = Component
	Component = function(obj) {
		let oldAttached = obj.attached || function() {}
		let oldDetached = obj.detached || function() {}
		obj.attached = function() {
			loadStore.call(this)
			this.setState = function(obj) {
				setState.call(this, obj)
			}
			oldAttached.call(this, ...arguments)
		}
		obj.detached = function() {
			unloadStore.call(this)
			oldDetached.call(this, ...arguments)
		}
		return oldComponent(obj)
	}
}

function setState(obj) {
	let keys = Object.keys(obj)
	let newObj = {}
	keys.forEach(key => {
		newObj['state.' + key] = obj[key]
	})
	_pages.forEach(item => {
		item.setData(newObj)
	})
}

function loadStore() {
	_pages.push(this)
	this.api = api
	this.setData({
		api: api,
		loading: 1,
		current_page: 0,
		last_page: 1
	})
}

function unloadStore() {
	let index = _pages.findIndex(item => {
		return item === this
	})
	if (index > -1) _pages.splice(index, 1)
}

initPage()
initComponent()
export default {
	api,
	store
}

import store from '@/store/index.js';